<template>
  <div class="cart-page">
    <el-card>
      <template #header>
        <div class="cart-header">
          <span class="title">🛒 我的购物车</span>
          <el-button 
            v-if="cartStore.items.length > 0" 
            type="danger" 
            text 
            @click="handleClearCart"
          >
            清空购物车
          </el-button>
        </div>
      </template>

      <!-- 加载中 -->
      <div v-if="cartStore.loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 购物车为空 -->
      <div v-else-if="cartStore.items.length === 0" class="empty-cart">
        <el-empty description="购物车是空的">
          <el-button type="primary" @click="goShopping">去逛逛</el-button>
        </el-empty>
      </div>

      <!-- 购物车列表 -->
      <div v-else class="cart-content">
        <!-- 全选 -->
        <div class="cart-toolbar">
          <el-checkbox 
            :model-value="isAllSelected" 
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <span class="selected-info">
            已选 {{ cartStore.selectedCount }} 件商品
          </span>
        </div>

        <!-- 商品列表 -->
        <div class="cart-items">
          <div 
            v-for="item in cartStore.items" 
            :key="item.id" 
            class="cart-item"
            :class="{ 'unavailable': !isItemAvailable(item) }"
          >
            <!-- 选择框 -->
            <div class="item-select">
              <el-checkbox 
                :model-value="item.checked" 
                @change="() => cartStore.toggleItemSelect(item.id)"
                :disabled="!isItemAvailable(item)"
              />
            </div>

            <!-- 商品图片 -->
            <div class="item-image">
              <img :src="getImageUrl(item.productImage)" :alt="item.productName" />
            </div>

            <!-- 商品信息 -->
            <div class="item-info">
              <div class="item-name">{{ item.productName }}</div>
              <div class="item-status">
                <el-tag v-if="item.status === 0" type="danger" size="small">已下架</el-tag>
                <el-tag v-else-if="item.stock < item.quantity" type="warning" size="small">
                  库存不足
                </el-tag>
                <el-tag v-else type="success" size="small">可购买</el-tag>
              </div>
            </div>

            <!-- 单价 -->
            <div class="item-price">
              <span class="price">¥{{ item.price }}</span>
            </div>

            <!-- 数量 -->
            <div class="item-quantity">
              <el-input-number
                :model-value="item.quantity"
                @change="(value) => handleQuantityChange(item.id, value)"
                :min="1"
                :max="item.stock"
                :disabled="!isItemAvailable(item)"
              />
              <div class="stock-info">库存: {{ item.stock }}</div>
            </div>

            <!-- 小计 -->
            <div class="item-subtotal">
              <span class="subtotal">¥{{ item.subtotal }}</span>
            </div>

            <!-- 操作 -->
            <div class="item-actions">
              <el-button 
                type="danger" 
                text 
                @click="handleRemove(item.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 结算栏 -->
        <div class="cart-footer">
          <div class="footer-left">
            <el-checkbox 
              :model-value="isAllSelected" 
              @change="handleSelectAll"
            >
              全选
            </el-checkbox>
          </div>

          <div class="footer-right">
            <div class="total-info">
              <span class="label">已选商品：</span>
              <span class="count">{{ cartStore.selectedCount }}</span>
              <span class="label">件</span>
            </div>
            <div class="total-price">
              <span class="label">合计：</span>
              <span class="price">¥{{ cartStore.selectedTotalPrice.toFixed(2) }}</span>
            </div>
            <el-button 
              type="primary" 
              size="large" 
              :disabled="cartStore.selectedCount === 0"
              @click="handleCheckout"
            >
              去结算
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 结算对话框 -->
    <el-dialog
      v-model="checkoutDialogVisible"
      title="确认订单"
      width="600px"
      @close="resetCheckoutForm"
    >
      <div class="checkout-dialog">
        <!-- 商品列表 -->
        <div class="checkout-items">
          <h4>订单商品</h4>
          <div v-for="item in selectedItemsForCheckout" :key="item.id" class="checkout-item">
            <img :src="getImageUrl(item.productImage)" class="item-thumb" />
            <div class="item-detail">
              <div class="item-name">{{ item.productName }}</div>
              <div class="item-price-qty">
                ¥{{ item.price }} × {{ item.quantity }}
              </div>
            </div>
            <div class="item-subtotal">¥{{ item.subtotal }}</div>
          </div>
        </div>

        <!-- 订单信息表单 -->
        <el-form :model="checkoutForm" label-width="100px" style="margin-top: 20px">
          <el-form-item label="支付方式" required>
            <el-radio-group v-model="checkoutForm.paymentMethod">
              <el-radio label="cash">现金</el-radio>
              <el-radio label="alipay">支付宝</el-radio>
              <el-radio label="wechat">微信支付</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="收货地址">
            <el-input
              v-model="checkoutForm.address"
              type="textarea"
              :rows="2"
              placeholder="请输入收货地址（可选）"
            />
          </el-form-item>
          
          <el-form-item label="联系电话">
            <el-input v-model="checkoutForm.phone" placeholder="请输入联系电话（可选）" />
          </el-form-item>
          
          <el-form-item label="备注">
            <el-input
              v-model="checkoutForm.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息（可选）"
            />
          </el-form-item>
        </el-form>

        <!-- 价格汇总 -->
        <div class="checkout-summary">
          <div class="summary-row">
            <span>商品总数：</span>
            <span>{{ selectedItemsForCheckout.length }} 件</span>
          </div>
          <div class="summary-row total">
            <span>订单金额：</span>
            <span class="total-price">¥{{ cartStore.selectedTotalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="checkoutDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submittingOrder" @click="submitOrder">
          确认下单
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createOrder } from '@/api/order'

const router = useRouter()
const cartStore = useCartStore()

// 结算对话框
const checkoutDialogVisible = ref(false)
const submittingOrder = ref(false)
const checkoutForm = reactive({
  paymentMethod: 'cash',
  address: '',
  phone: '',
  remark: ''
})
const selectedItemsForCheckout = ref([])

// 是否全选
const isAllSelected = computed(() => {
  if (cartStore.items.length === 0) return false
  const availableItems = cartStore.items.filter(item => isItemAvailable(item))
  if (availableItems.length === 0) return false
  return availableItems.every(item => item.checked)
})

// 是否部分选中
const isIndeterminate = computed(() => {
  const checkedCount = cartStore.items.filter(item => item.checked).length
  return checkedCount > 0 && checkedCount < cartStore.items.filter(item => isItemAvailable(item)).length
})

// 检查商品是否可购买
const isItemAvailable = (item) => {
  return item.status === 1 && item.stock >= item.quantity
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/80'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return 'http://localhost:8080' + url
}

// 加载购物车
onMounted(async () => {
  try {
    await cartStore.loadCart()
  } catch (error) {
    console.error('购物车初始化失败:', error)
  }
})

// 全选/取消全选
const handleSelectAll = (checked) => {
  cartStore.toggleSelectAll(checked)
}

// 更新商品数量
const handleQuantityChange = async (cartId, quantity) => {
  await cartStore.updateQuantity(cartId, quantity)
}

// 删除商品
const handleRemove = async (cartId) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await cartStore.removeItem(cartId)
  } catch (error) {
    // 用户取消
  }
}

// 清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      type: 'warning'
    })
    await cartStore.clearCartItems()
  } catch (error) {
    // 用户取消
  }
}

// 去逛逛
const goShopping = () => {
  router.push('/customer/products')
}

// 显示结算对话框
const showCheckoutDialog = (items) => {
  selectedItemsForCheckout.value = items
  checkoutDialogVisible.value = true
}

// 去结算
const handleCheckout = async () => {
  if (cartStore.selectedCount === 0) {
    ElMessage.warning('请先选择商品')
    return
  }
  
  // 获取选中的商品
  const selectedItems = cartStore.getSelectedItems()
  
  // 检查所有选中商品是否可购买
  const unavailableItems = selectedItems.filter(item => !isItemAvailable(item))
  if (unavailableItems.length > 0) {
    ElMessage.warning('选中的商品中有已下架或库存不足的商品，请取消选择后再结算')
    return
  }
  
  // 显示结算对话框
  showCheckoutDialog(selectedItems)
}

// 提交订单
const submitOrder = async () => {
  if (selectedItemsForCheckout.value.length === 0) {
    ElMessage.warning('请选择商品')
    return
  }
  
  submittingOrder.value = true
  try {
    const orderData = {
      cartIds: selectedItemsForCheckout.value.map(item => item.id),
      paymentMethod: checkoutForm.paymentMethod,
      address: checkoutForm.address || null,
      phone: checkoutForm.phone || null,
      remark: checkoutForm.remark || null
    }
    
    const res = await createOrder(orderData)
    if (res.code === 200) {
      ElMessage.success('订单创建成功')
      checkoutDialogVisible.value = false
      // 刷新购物车
      await cartStore.loadCart()
      // 跳转到订单列表
      router.push('/customer/orders')
    } else {
      ElMessage.error(res.message || '订单创建失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error(error.response?.data?.message || '订单创建失败')
  } finally {
    submittingOrder.value = false
  }
}

// 重置结算表单
const resetCheckoutForm = () => {
  checkoutForm.paymentMethod = 'cash'
  checkoutForm.address = ''
  checkoutForm.phone = ''
  checkoutForm.remark = ''
  selectedItemsForCheckout.value = []
}
</script>

<style lang="scss" scoped>
.cart-page {
  padding: 20px;

  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 20px;
      font-weight: bold;
    }
  }

  .loading-container {
    padding: 20px;
  }

  .empty-cart {
    padding: 60px 0;
    text-align: center;
  }

  .cart-content {
    .cart-toolbar {
      display: flex;
      align-items: center;
      gap: 20px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
      margin-bottom: 15px;

      .selected-info {
        color: #606266;
        font-size: 14px;
      }
    }

    .cart-items {
      .cart-item {
        display: flex;
        align-items: center;
        gap: 20px;
        padding: 20px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        margin-bottom: 15px;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        &.unavailable {
          background-color: #fafafa;
          opacity: 0.7;
        }

        .item-select {
          flex-shrink: 0;
        }

        .item-image {
          flex-shrink: 0;
          width: 80px;
          height: 80px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
          }
        }

        .item-info {
          flex: 1;
          min-width: 200px;

          .item-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
          }

          .item-status {
            margin-top: 8px;
          }
        }

        .item-price {
          flex-shrink: 0;
          width: 100px;
          text-align: center;

          .price {
            font-size: 18px;
            color: #ff4d4f;
            font-weight: bold;
          }
        }

        .item-quantity {
          flex-shrink: 0;
          width: 150px;
          text-align: center;

          .stock-info {
            margin-top: 5px;
            font-size: 12px;
            color: #909399;
          }
        }

        .item-subtotal {
          flex-shrink: 0;
          width: 120px;
          text-align: center;

          .subtotal {
            font-size: 20px;
            color: #ff4d4f;
            font-weight: bold;
          }
        }

        .item-actions {
          flex-shrink: 0;
          width: 80px;
          text-align: center;
        }
      }
    }

    .cart-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      background-color: #fff;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      margin-top: 20px;
      position: sticky;
      bottom: 0;
      z-index: 10;

      .footer-left {
        flex: 1;
      }

      .footer-right {
        display: flex;
        align-items: center;
        gap: 30px;

        .total-info {
          font-size: 14px;
          color: #606266;

          .count {
            color: #ff4d4f;
            font-weight: bold;
            font-size: 18px;
            margin: 0 5px;
          }
        }

        .total-price {
          .label {
            font-size: 16px;
            color: #606266;
          }

          .price {
            font-size: 28px;
            color: #ff4d4f;
            font-weight: bold;
            margin-left: 10px;
          }
        }
      }
    }
  }
}

// 结算对话框样式
  .checkout-dialog {
    .checkout-items {
      h4 {
        margin-bottom: 15px;
        font-size: 16px;
        color: #303133;
      }

      .checkout-item {
        display: flex;
        align-items: center;
        gap: 15px;
        padding: 10px;
        background-color: #f5f7fa;
        border-radius: 4px;
        margin-bottom: 10px;

        .item-thumb {
          width: 60px;
          height: 60px;
          object-fit: cover;
          border-radius: 4px;
        }

        .item-detail {
          flex: 1;

          .item-name {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 5px;
          }

          .item-price-qty {
            font-size: 12px;
            color: #909399;
          }
        }

        .item-subtotal {
          font-size: 16px;
          color: #ff4d4f;
          font-weight: bold;
        }
      }
    }

    .checkout-summary {
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
      margin-top: 20px;

      .summary-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        font-size: 14px;

        &.total {
          margin-bottom: 0;
          padding-top: 10px;
          border-top: 1px dashed #dcdfe6;

          .total-price {
            font-size: 24px;
            color: #ff4d4f;
            font-weight: bold;
          }
        }
      }
    }
  }

// 响应式设计
@media (max-width: 768px) {
  .cart-page {
    padding: 10px;

    .cart-items {
      .cart-item {
        flex-wrap: wrap;
        gap: 10px;

        .item-info {
          min-width: 100%;
        }
      }
    }

    .cart-footer {
      flex-direction: column;
      gap: 15px;

      .footer-right {
        width: 100%;
        flex-direction: column;
        gap: 10px;
      }
    }
  }
}
</style>
